package net.lesscoding.rpc.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LoggingHandler;
import net.lesscoding.common.Const;
import net.lesscoding.protocol.ProtocolFrameDecoder;
import net.lesscoding.protocol.SharedMessageCodec;
import net.lesscoding.rpc.handler.RpcRequestMessageHandler;

/**
 * @author eleven
 * @date 2024/12/4 8:30
 * @apiNote
 */
public class RpcServer {
    public static void main(String[] args) {
        NioEventLoopGroup boss = new NioEventLoopGroup();
        NioEventLoopGroup worker = new NioEventLoopGroup();
        LoggingHandler logger = new LoggingHandler();
        SharedMessageCodec messageCodec = new SharedMessageCodec();
        RpcRequestMessageHandler rpcRequestHandler = new RpcRequestMessageHandler();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap()
                    .group(boss, worker)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<NioSocketChannel>() {
                        @Override
                        protected void initChannel(NioSocketChannel ch) throws Exception {
                            ch.pipeline()
                                    .addLast(new ProtocolFrameDecoder())
                                    .addLast(logger)
                                    .addLast(messageCodec)
                                    .addLast(rpcRequestHandler);
                        }
                    });
            ChannelFuture future = serverBootstrap.bind(Const.PORT).sync();
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }

    }
}
